package com.starry.compose_study.state.two

import android.app.Activity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doAfterTextChanged
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.viewModelFactory
import com.starry.compose_study.databinding.ActivityUnStructureBinding

class SingleDataFlowActivity : AppCompatActivity() {

    private val binding by lazy {
        ActivityUnStructureBinding.inflate(layoutInflater)
    }
    private val viewModel: HelloViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(binding.root)

        binding.editTextText.doAfterTextChanged { text ->
            viewModel.onNameChanged(text.toString())
        }
        viewModel.name.observe(this) { name ->
            binding.textView.text = name
        }
    }

}


class HelloViewModel : ViewModel() {

    //私有的状态，可读可写
    private val _name = MutableLiveData("")
    //这个属性只读的，外部只需要监听name的变化
    val name: LiveData<String> = _name
    //状态的改变只交给ViewModel
    fun onNameChanged(newName: String) {
        _name.value = newName
    }
}